﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using KSAWPFExtensions;
using KSASupport;
using KSASupport.BlobTracking;
using PhotoLoader;
using System.IO;
using System.Windows.Ink;

using System.Net;
using System.Xml.Linq;

namespace KSAWPFDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class HomeAuto : UserControl
    {
        //const string ipAddress = @"192.168.137.193:49451";
        const string ipAddress = @"http://192.168.137.228:49451";
        const string oldIP      = @"http://192.168.2.7:3480";
        const string deviceID1 = ipAddress + "/data_request?id=action&DeviceNum=3&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=";
        string demo = @"http://192.168.137.194:49451";
        string On = deviceID1 + "1";
        string Off = deviceID1 + "0";
        string Status = ipAddress + @"data_request?id=lu_sdata&output_format=xml";

        public HomeAuto()
        {
            InitializeComponent();
            this.Loaded += HomeAuto_Loaded;
            this.Unloaded += HomeAuto_Unloaded;
            if(File.Exists(@"C:\KSA\TOSCOMM028.mp4"))
            {
              media.Source= new Uri(@"C:\KSA\TOSCOMM028.mp4");
            }
        }

        void HomeAuto_Unloaded(object sender, RoutedEventArgs e)
        {
            // Fun behind the scenes...at maker faire it was so hot that Lou decided turning the fan on when we exited the home automation demo was a good idea
            // thus...the source below...
            //SendRequest(On);
        }

        void HomeAuto_Loaded(object sender, RoutedEventArgs e)
        {
            SendRequest(Off);

            Image onIcon = new Image();
            onIcon.Source = new BitmapImage(new Uri(@"C:\KSA\KSAWPFDemo\HomeAutomation\Images\FanOff.png", UriKind.Relative));
            ImageBrush imgBrush = new ImageBrush(onIcon.Source);
            FanToggleButton.Background = imgBrush;
            FanToggleButton.Tag = "ON";
        }

        private void SendMessage(object sender, TouchEventArgs e)
        {
            FrameworkElement button = sender as FrameworkElement;
            if (button == null)
                return;
            ((Button)button).Background = Brushes.Red; // highlight the button for feedback
            button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            e.Handled = true;
        }

        private void SendMessageClick(object sender, RoutedEventArgs e)
        {
            Button button = e.Source as Button;
            if(button != null)
            {
               WebBrowser browser = new WebBrowser();
               string tag = button.Tag as string;
               string resp = "";
               switch(tag)
               {
                    case("ON"):
                        {
                            resp = SendRequest(On);

                            Image onIcon = new Image();
                            onIcon.Source = new BitmapImage(new Uri(@"C:\KSA\KSAWPFDemo\HomeAutomation\Images\FanOn.png", UriKind.Relative));
                            ImageBrush imgBrush = new ImageBrush(onIcon.Source);
                            FanToggleButton.Background = imgBrush;
                            FanToggleButton.Tag = "OFF";

                          break;
                        }
                    case ("OFF"):
                        {
                            resp = SendRequest(Off);

                            Image onIcon = new Image();
                            onIcon.Source = new BitmapImage(new Uri(@"C:\KSA\KSAWPFDemo\HomeAutomation\Images\FanOff.png", UriKind.Relative));
                            ImageBrush imgBrush = new ImageBrush(onIcon.Source);
                            FanToggleButton.Background = imgBrush;
                            FanToggleButton.Tag = "ON";

                            break;
                        }
               }
               StatusLabel.Content = resp;
               System.Threading.Thread.Sleep(500);
               string xml = SendRequest(Status);
               
                try
                {
                    XDocument xDoc = XDocument.Parse(xml);
                    // BUGBUG: Sloppy demo parsing...I know I'm working with one device currently...
                    string power = xDoc.Descendants("device").Attributes("watts").First().Value;
                    string kwh = xDoc.Descendants("device").Attributes("kwh").First().Value;
                    PowerLabel.Content = "Watts: " + power + "  KWH: " + kwh;
                    
                       
                }
                catch (Exception)
                { // ignore
                }
               
            }
        }
        private string SendRequest(string request)
        {
            try
            {
                Uri myUriOn = new Uri(request);
                WebRequest myWebRequest = WebRequest.Create(myUriOn);
                WebResponse myWebResponse = myWebRequest.GetResponse();
                StreamReader reader = new StreamReader(myWebResponse.GetResponseStream());
                string resp = reader.ReadToEnd();
                myWebResponse.Close();
                return resp;
            }
            catch(Exception)
            {
                return "Error";
            }

        }

        private void MediaTimeline_Completed(object sender, EventArgs e)
        {
            media.Play();
        }
    }
      
}
